import Vue from 'vue'
import Vuex from 'vuex'
import { changeTheme, autoTheme, watchSystemTheme } from '@/utils/theme'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    currentTheme: localStorage.getItem('theme') || 'light',
    categories: [],
    currentCategory: null
  },
  mutations: {
    SET_THEME(state, theme) {
      state.currentTheme = theme
      localStorage.setItem('theme', theme)
    },
    SET_CATEGORIES(state, categories) {
      state.categories = categories
    },
    SET_CURRENT_CATEGORY(state, category) {
      state.currentCategory = category
    }
  },
  actions: {
    toggleTheme({ commit, state }) {
      const newTheme = state.currentTheme === 'light' ? 'dark' : 'light'
      commit('SET_THEME', newTheme)
      changeTheme(newTheme)
    },
    initTheme({ commit }) {
      const savedTheme = localStorage.getItem('theme')
      const systemTheme = watchSystemTheme()
      const theme = savedTheme || systemTheme || 'light'
      commit('SET_THEME', theme)
      changeTheme(theme)
    }
  }
})
